﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsForms切换
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // 方法1: 直接启动主窗体
            //Application.Run(new MainForm());

            // 方法2: 使用ApplicationContext管理窗体
             Application.Run(new FormManager());
        }
    }

    // 窗体管理器
    public class FormManager : ApplicationContext
    {
        private static FormManager _instance;
        public static FormManager Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new FormManager();
                return _instance;
            }
        }

        private Form _currentForm;

        public FormManager()
        {
            // 显示主窗体
            ShowForm(new MainForm());
        }

        public void ShowForm(Form form)
        {
            if (_currentForm != null)
            {
                _currentForm.Hide();
                _currentForm.FormClosed -= CurrentForm_FormClosed;
            }

            _currentForm = form;
            _currentForm.FormClosed += CurrentForm_FormClosed;
            _currentForm.Show();
        }

        private void CurrentForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 如果没有打开的窗体，退出应用
            if (Application.OpenForms.Count == 0)
            {
                ExitThread();
            }
        }

        public void ExitApplication()
        {
            ExitThread();
        }
    }
}
